package org.jeecg.modules.wxchar.controller;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.*;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.vdurmont.emoji.EmojiParser;
import io.swagger.models.auth.In;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.plantation.entity.Product;
import org.jeecg.modules.plantation.service.IProductService;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.service.ISysUserService;
import org.jeecg.modules.wxchar.entity.NeedRelease;
import org.jeecg.modules.wxchar.service.INeedReleaseService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

 /**
 * @Description: 供需发布情况
 * @Author: jeecg-boot
 * @Date:   2019-08-29
 * @Version: V1.0
 */
@Slf4j
@Api(tags="供需发布情况")
@RestController
@RequestMapping("/wxchar/needRelease")
public class NeedReleaseController {
	@Autowired
	private INeedReleaseService needReleaseService;
	@Autowired
	private IProductService productService;
	
	/**
	 * 分页列表查询
	 * @param needRelease
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "供需发布情况-分页列表查询")
	@ApiOperation(value="供需发布情况-分页列表查询", notes="供需发布情况-分页列表查询")
	@GetMapping(value = "/list")
	public Result<IPage<NeedRelease>> queryPageList(NeedRelease needRelease,
									  @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
									  @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
									  HttpServletRequest req) {
		Result<IPage<NeedRelease>> result = new Result<IPage<NeedRelease>>();
		needRelease.setStatus("0");
		QueryWrapper<NeedRelease> queryWrapper = QueryGenerator.initQueryWrapper(needRelease, req.getParameterMap());
		queryWrapper.orderByDesc("create_time");
		Page<NeedRelease> page = new Page<NeedRelease>(pageNo, pageSize);
		IPage<NeedRelease> pageList = needReleaseService.page(page, queryWrapper);
		List<NeedRelease> list = new ArrayList<NeedRelease>();
		for(int i = 0;i < pageList.getRecords().size() ;i++){
			NeedRelease needRelease1 = (NeedRelease) pageList.getRecords().get(i);
			Product product = productService.getById(needRelease1.getBread());
			//SysUser sysUser = sysUserService.getById(needRelease1.getCreateBy());
			if(product != null ){
				needRelease1.setBreadName(product.getProductName());
			}
			needRelease1.setCreateBy(EmojiParser.parseToUnicode(needRelease1.getCreateBy()));
			/*if(sysUser != null ){
				needRelease1.setCreateBy(sysUser.getRealname());
			}*/
			list.add(needRelease1);
		}
		pageList.setRecords(list);
		result.setSuccess(true);
		result.setResult(pageList);
		return result;
	}

	 /**
	  * 历史列表查询
	  * @param needRelease
	  * @param pageNo
	  * @param pageSize
	  * @param req
	  * @return
	  */
	 @AutoLog(value = "历史列表查询")
	 @ApiOperation(value="历史列表查询", notes="历史列表查询")
	 @GetMapping(value = "/history")
	 public Result<IPage<NeedRelease>> historyList(NeedRelease needRelease,
													 @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
													 @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
													 HttpServletRequest req) {
		 Result<IPage<NeedRelease>> result = new Result<IPage<NeedRelease>>();
		 LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		 needRelease.setCreateBy(sysUser.getRealname());
		 QueryWrapper<NeedRelease> queryWrapper = QueryGenerator.initQueryWrapper(needRelease, req.getParameterMap());
		 Page<NeedRelease> page = new Page<NeedRelease>(pageNo, pageSize);
		 IPage<NeedRelease> pageList = needReleaseService.page(page, queryWrapper);
		 List<NeedRelease> list = new ArrayList<NeedRelease>();
		 for(int i = 0;i < pageList.getRecords().size() ;i++){
			 NeedRelease needRelease1 = (NeedRelease) pageList.getRecords().get(i);
			 Product product = productService.getById(needRelease1.getBread());
			 if(product != null ){
				 needRelease1.setBreadName(product.getProductName());
			 }
			 needRelease1.setCreateBy(EmojiParser.parseToUnicode(needRelease1.getCreateBy()));
			 list.add(needRelease1);
		 }
		 pageList.setRecords(list);
		 result.setSuccess(true);
		 result.setResult(pageList);
		 return result;
	 }

	 /**
	  * 公告列表查询
	  * @param needRelease
	  * @param pageNo
	  * @param pageSize
	  * @param req
	  * @return
	  */
	 @AutoLog(value = "公告列表查询")
	 @ApiOperation(value="公告列表查询", notes="公告列表查询")
	 @GetMapping(value = "/inform")
	 public Result<IPage<NeedRelease>> inform(NeedRelease needRelease,
												   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
												   @RequestParam(name="pageSize", defaultValue="5") Integer pageSize,
												   HttpServletRequest req) {
		 Result<IPage<NeedRelease>> result = new Result<IPage<NeedRelease>>();
		 needRelease.setStatus("1");
		 QueryWrapper<NeedRelease> queryWrapper = QueryGenerator.initQueryWrapper(needRelease, req.getParameterMap());
		 Page<NeedRelease> page = new Page<NeedRelease>(pageNo, pageSize);
		 IPage<NeedRelease> pageList = needReleaseService.page(page, queryWrapper);
		 List<NeedRelease> list = new ArrayList<NeedRelease>();
		 for(int i = 0;i < pageList.getRecords().size() ;i++){
			 NeedRelease needRelease1 = (NeedRelease) pageList.getRecords().get(i);
			 needRelease1.setCreateBy(EmojiParser.parseToUnicode(needRelease1.getCreateBy()));
			 list.add(needRelease1);
		 }
		 pageList.setRecords(list);
		 result.setSuccess(true);
		 result.setResult(pageList);
		 return result;
	 }
	
	/**
	  *   添加
	 * @param needRelease
	 * @return
	 */
	@AutoLog(value = "供需发布情况-添加")
	@ApiOperation(value="供需发布情况-添加", notes="供需发布情况-添加")
	@PostMapping(value = "/add")
	public Result<NeedRelease> add(@RequestBody NeedRelease needRelease) {
		Result<NeedRelease> result = new Result<NeedRelease>();
		try {
			LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
			needRelease.setCreateBy(sysUser.getRealname());
			needRelease.setStatus("0");
			needReleaseService.save(needRelease);
			result.success("添加成功！");
		} catch (Exception e) {
			log.error(e.getMessage(),e);
			result.error500("操作失败");
		}
		return result;
	}
	
	/**
	  *  编辑
	 * @param needRelease
	 * @return
	 */
	@AutoLog(value = "供需发布情况-编辑")
	@ApiOperation(value="供需发布情况-编辑", notes="供需发布情况-编辑")
	@PutMapping(value = "/edit")
	public Result<NeedRelease> edit(@RequestBody NeedRelease needRelease) {
		Result<NeedRelease> result = new Result<NeedRelease>();
		NeedRelease needReleaseEntity = needReleaseService.getById(needRelease.getId());
		if(needReleaseEntity==null) {
			result.error500("未找到对应实体");
		}else {
			boolean ok = needReleaseService.updateById(needRelease);
			//TODO 返回false说明什么？
			if(ok) {
				result.success("修改成功!");
			}
		}
		
		return result;
	}

	 /**
	  *   通过id修改状态
	  * @param id
	  * @return
	  */
	 @AutoLog(value = "通过id修改状态")
	 @ApiOperation(value="通过id修改状态", notes="通过id修改状态")
	 @PostMapping(value = "/updateStatus")
	 public Result<?> updateStatus(@RequestParam(name="id",required=true) String id) {
		 Result<NeedRelease> result = new Result<NeedRelease>();
		 NeedRelease needReleaseEntity = needReleaseService.getById(id);
		 if(needReleaseEntity==null) {
			 result.error500("未找到对应实体");
		 }else {
			 needReleaseEntity.setStatus("1");
			 boolean ok = needReleaseService.updateById(needReleaseEntity);
			 //TODO 返回false说明什么？
			 if(ok) {
				 result.success("修改成功!");
			 }
		 }
		 return Result.ok("删除成功!");
	 }

	
	/**
	  *   通过id删除
	 * @param id
	 * @return
	 */
	@AutoLog(value = "供需发布情况-通过id删除")
	@ApiOperation(value="供需发布情况-通过id删除", notes="供需发布情况-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		try {
			needReleaseService.removeById(id);
		} catch (Exception e) {
			log.error("删除失败",e.getMessage());
			return Result.error("删除失败!");
		}
		return Result.ok("删除成功!");
	}
	
	/**
	  *  批量删除
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "供需发布情况-批量删除")
	@ApiOperation(value="供需发布情况-批量删除", notes="供需发布情况-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<NeedRelease> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		Result<NeedRelease> result = new Result<NeedRelease>();
		if(ids==null || "".equals(ids.trim())) {
			result.error500("参数不识别！");
		}else {
			this.needReleaseService.removeByIds(Arrays.asList(ids.split(",")));
			result.success("删除成功!");
		}
		return result;
	}
	
	/**
	  * 通过id查询
	 * @param id
	 * @return
	 */
	@AutoLog(value = "供需发布情况-通过id查询")
	@ApiOperation(value="供需发布情况-通过id查询", notes="供需发布情况-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<NeedRelease> queryById(@RequestParam(name="id",required=true) String id) {
		Result<NeedRelease> result = new Result<NeedRelease>();
		NeedRelease needRelease = needReleaseService.getById(id);
		if(needRelease==null) {
			result.error500("未找到对应实体");
		}else {
			result.setResult(needRelease);
			result.setSuccess(true);
		}
		return result;
	}

	 @AutoLog(value = "按type分组统计")
	 @ApiOperation(value="按type分组统计", notes="按type分组统计")
	 @GetMapping(value = "/groupByType")
	 public Result<Map<String,Integer>> groupByType() {
		 Result<Map<String,Integer>> result = new Result<Map<String,Integer>>();
		 LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		 Map<String,Integer> map = new HashMap<String,Integer>();
		 if(sysUser != null ){
			 List<Map<String,Object>> list = needReleaseService.groupByType(sysUser.getUsername());
			 if(list == null || list.size() == 0){
				 map.put("score",0);
				 map.put("buy",0);
				 map.put("workOff",0);
			 }else if(list != null && list.size() == 1){
			 	int sum = 0;
			 	for (Map<String,Object> map1 :list){
					Integer type = Integer.parseInt(map1.get("type").toString());
			 		if (type == 1){
						map.put("buy",Integer.parseInt(map1.get("sum").toString()));
					}else{
						map.put("buy",0);
					}
					if (type == 2 ){
						map.put("workOff",Integer.parseInt(map1.get("sum").toString()));
					}else{
						map.put("workOff",0);
					}
					sum += map.get("sum");

				}
			 	map.put("score",sum * 5);
			 }else{
				 int sum = 0;
				 for (Map<String,Object> map1 :list){
				 	 Integer type = Integer.parseInt(map1.get("type").toString());
					 if (type != null && type == 1){
						 map.put("buy", Integer.parseInt(map1.get("sum").toString()));
					 }
					 if (type != null && type == 2){
						 map.put("workOff",Integer.parseInt(map1.get("sum").toString()));
					 }
					 sum += Integer.parseInt(map1.get("sum").toString());
				 }
				 map.put("score",sum * 5);
			 }
		 }
		 result.setResult(map);
		 return result;
	 }

	 @AutoLog(value = "按type分组统计")
	 @ApiOperation(value="按type分组统计", notes="按type分组统计")
	 @GetMapping(value = "/scoreList")
	 public Result<Map<String,Object>> scoreList() {
		 Result<Map<String,Object>> result = new Result<Map<String,Object>>();
		 LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		 Map<String,Object> map = new HashMap<>();
		 Date d = new Date();//获取当前时间    
		 Calendar calendar = Calendar.getInstance();
		 calendar.setTime(d);
		 calendar.add(Calendar.MONTH, -6);//当前时间前去一个月，即一个月前的时间
		 List<Object> month = new ArrayList<Object>();
		 List<Object> score = new ArrayList<Object>();
		 Integer sum = 0;
		 if(sysUser != null ){
			for (int i = 0; i < 6 ; i++ ){
				Date date = calendar.getTime();
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
				sum += needReleaseService.scoreList(sysUser.getRealname(),sdf.format(date));
				sdf = new SimpleDateFormat("MM月");
				month.add(sdf.format(date));
				score.add(sum * 5);
				calendar.add(Calendar.MONTH, 1);
			}
		 }
		 map.put("month",month);
		 map.put("score",score);
		 result.setResult(map);
		 return result;
	 }

	 @Value(value = "${jeecg.path.upload}")
	 private String uploadpath;


	 @PostMapping(value = "/upload")
	 public Result<?> upload(HttpServletRequest request, HttpServletResponse response) {
	 	System.out.println("图片导入开始");
		 Result<?> result = new Result<>();
		 try {
			 String ctxPath = uploadpath;
			 String fileName = null;
			 String bizPath = "files";
			 String nowday = new SimpleDateFormat("yyyyMMdd").format(new Date());
			 File file = new File(ctxPath + File.separator + bizPath + File.separator + nowday);
			 if (!file.exists()) {
				 file.mkdirs();// 创建文件根目录
			 }
			 MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
			 MultipartFile mf = multipartRequest.getFile("file");// 获取上传文件对象
			 String orgName = mf.getOriginalFilename();// 获取文件名
			 fileName = UUID.randomUUID().toString() + orgName.substring(orgName.indexOf("."));

			 String savePath = file.getPath() + File.separator + fileName;
			 File savefile = new File(savePath);
			 FileCopyUtils.copy(mf.getBytes(), savefile);
			 String dbpath = bizPath + File.separator + nowday + File.separator + fileName;
			 if (dbpath.contains("\\")) {
				 dbpath = dbpath.replace("\\", "/");
			 }
			 result.setMessage(dbpath);
			 result.setSuccess(true);
		 } catch (IOException e) {
			 result.setSuccess(false);
			 result.setMessage(e.getMessage());
			 log.error(e.getMessage(), e);
		 }
		 return result;
	 }

  /**
      * 导出excel
   *
   * @param request
   * @param response
   */
  @RequestMapping(value = "/exportXls")
  public ModelAndView exportXls(HttpServletRequest request, HttpServletResponse response) {
      // Step.1 组装查询条件
      QueryWrapper<NeedRelease> queryWrapper = null;
      try {
          String paramsStr = request.getParameter("paramsStr");
          if (oConvertUtils.isNotEmpty(paramsStr)) {
              String deString = URLDecoder.decode(paramsStr, "UTF-8");
              NeedRelease needRelease = JSON.parseObject(deString, NeedRelease.class);
              queryWrapper = QueryGenerator.initQueryWrapper(needRelease, request.getParameterMap());
          }
      } catch (UnsupportedEncodingException e) {
          e.printStackTrace();
      }

      //Step.2 AutoPoi 导出Excel
      ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
      List<NeedRelease> pageList = needReleaseService.list(queryWrapper);
      //导出文件名称
      mv.addObject(NormalExcelConstants.FILE_NAME, "供需发布情况列表");
      mv.addObject(NormalExcelConstants.CLASS, NeedRelease.class);
      mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("供需发布情况列表数据", "导出人:Jeecg", "导出信息"));
      mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
      return mv;
  }

  /**
      * 通过excel导入数据
   *
   * @param request
   * @param response
   * @return
   */
  @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
  public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
      MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
      Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
      for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
          MultipartFile file = entity.getValue();// 获取上传文件对象
          ImportParams params = new ImportParams();
          params.setTitleRows(2);
          params.setHeadRows(1);
          params.setNeedSave(true);
          try {
              List<NeedRelease> listNeedReleases = ExcelImportUtil.importExcel(file.getInputStream(), NeedRelease.class, params);
              needReleaseService.saveBatch(listNeedReleases);
              return Result.ok("文件导入成功！数据行数:" + listNeedReleases.size());
          } catch (Exception e) {
              log.error(e.getMessage(),e);
              return Result.error("文件导入失败:"+e.getMessage());
          } finally {
              try {
                  file.getInputStream().close();
              } catch (IOException e) {
                  e.printStackTrace();
              }
          }
      }
      return Result.ok("文件导入失败！");
  }

}
